#include <algorithm>

#include "Page.h"
#include "Miscellaneous.h"
#include "ElementFactory.h"

using namespace std;

CPage::CPage(IXmlReader* pReader) throw(...)
{
	InitPageFromXml(pReader);
}


CPage::~CPage(void)
{
}

const vector<unique_ptr<CElement>>* CPage::GetElements() const
{
	return &_ve;
}

const wstring& CPage::GetUrl() const
{
	return _url;
}

void CPage::InitPageFromXml(IXmlReader* pReader) throw(...)
{
	HRESULT hr;
	XmlNodeType nodeType;

	//
	_url = CMiscellaneous::GetAttributeValue(pReader, L"url");
	_name = CMiscellaneous::GetAttributeValue(pReader, L"name");
	//

	// read until there are no more nodes
	if (!pReader->IsEmptyElement())
		while (S_OK == (hr = pReader->Read(&nodeType))) {

			bool skip = false;
			switch (nodeType)
			{
			case XmlNodeType_Element:
				{
					_ve.push_back(CElementFactory::Create(pReader));
				}
				break;
			case XmlNodeType_EndElement:
				{
					if(CMiscellaneous::GetLocalName(pReader) == L"html")
						skip = true;
				}
				break;
			}
			if (skip)
				break;

		}

		//
}

void CPage::Fill(IHTMLDocument2* document) throw(...)
{
	// Workaround for IE7
	if(CMiscellaneous::GetIEMajorVersion() == 7 && 
		this->ContainsActiveX())
		CMiscellaneous::WorkaroundForIE7(document);

	// Fill every element
	auto ve = this->GetElements();
	for_each(ve->cbegin(), ve->cend(), [document](vector<unique_ptr<CElement>>::const_reference e){
		e->DoFill(document);
	});
}

bool CPage::ContainsActiveX() const throw()
{
	auto ve = this->GetElements();
	auto it = find_if(ve->cbegin(), ve->cend(), [](vector<unique_ptr<CElement>>::const_reference e) -> bool {
		return e->IsActiveX();
	});

	return it != ve->cend();
}